package com.oceanstar.service.Impl;

import com.oceanstar.Pojo.*;
import com.oceanstar.mapper.ChaperonMapper;
import com.oceanstar.service.IChaperonService;
import com.oceanstar.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ChaperonServiceImpl implements IChaperonService {
    // 注入mapper
    private final ChaperonMapper chaperonMapper;
    // 构造器注入
    public ChaperonServiceImpl(ChaperonMapper chaperonMapper) {
        this.chaperonMapper = chaperonMapper;
    }

    /*
     *新增陪诊人员
     */
    @Override
    public void addChaperon(ChaperonInfo chaperonInfo, String token) throws Exception {
        Claims claims = JwtUtils.parseToken(token);
        Integer identity = (Integer) claims.get("identity");
        if (identity != 3) {
            throw new Exception("需为管理员权限");
        }
        chaperonMapper.insertChaperon(chaperonInfo);
    }

    /*
     *删除陪诊人员
     */
    @Override
    public void deleteChaperon(Integer id, String token) throws Exception {
        Claims claims = JwtUtils.parseToken(token);
        Integer identity = (Integer) claims.get("identity");
        if (identity != 3) {
            throw new Exception("需为管理员权限");
        }
        // 检查该用户是否存在
        if (chaperonMapper.selectChaperonById(id) == null) {
            throw new Exception("该陪诊人员不存在");
        }
        chaperonMapper.deleteChaperonById(id);
    }

    /*
     *修改陪诊人员信息
     */
    @Override
    public void updateChaperonInfo(ChaperonInfo chaperonInfo) throws Exception {
        // 检查该用户是否存在
        if (chaperonMapper.selectChaperonById(chaperonInfo.getId()) == null) {
            throw new Exception("该陪诊人员不存在");
        }
        ChaperonInfo oldChaperonInfo = chaperonMapper.selectChaperonById(chaperonInfo.getId());
        if (chaperonInfo.getName() == null) {chaperonInfo.setName(oldChaperonInfo.getName());}
        if (chaperonInfo.getGender() == null) {chaperonInfo.setGender(oldChaperonInfo.getGender());}
        if (chaperonInfo.getPhone() == null) {chaperonInfo.setPhone(oldChaperonInfo.getPhone());}
        if (chaperonInfo.getIntroduction() == null) {chaperonInfo.setIntroduction(oldChaperonInfo.getIntroduction());}
        chaperonMapper.updateChaperonInfo(chaperonInfo);
    }

    /*
     *查询所有陪诊人员的数据信息
     */
    @Override
    public List<ChaperonInfo> getAllChaperonInfo() {
        return chaperonMapper.getAllChaperon();
    }

    /*
     *查询陪诊人员的数据信息
     */
    @Override
    public ChaperonInfo getChaperonInfo(Integer id) throws Exception {
        // 检查该用户是否存在
        if (chaperonMapper.selectChaperonById(id) == null) {
            throw new Exception("该陪诊人员不存在");
        }
        return chaperonMapper.selectChaperonById(id);
    }

    /*
     *管理员发布新的陪诊服务
     */
    @Override
    public void updateServicesInfo(ServiceInfo serviceInfo, String token) throws Exception {
        Claims claims = JwtUtils.parseToken(token);
        Integer identity = (Integer) claims.get("identity");
        if (identity != 3) {
            throw new Exception("需为管理员权限");
        }
        chaperonMapper.insertServices(serviceInfo);
    }

    /*
     *管理员获取陪诊列表
     */
    @Override
    public PageInfo<Services> getServicesList(String token) throws Exception {
        Claims claims = JwtUtils.parseToken(token);
        Integer identity = (Integer) claims.get("identity");
        if (identity != 3) {
            throw new Exception("需为管理员权限");
        }
        // 查询数据
        List<ServiceInfo> servicesInfoList = chaperonMapper.selectServicesList();

        //转换为Services对象列表
        List<Services> servicesList = servicesInfoList.stream().map(serviceInfo -> {
            Services service = new Services();
            service.setId(serviceInfo.getId());
            service.setChaperonId(serviceInfo.getChaperonId());
            service.setDate(serviceInfo.getServiceDate());

            // 查询陪诊人员详细信息
            ChaperonInfo chaperon = chaperonMapper.selectChaperonById(serviceInfo.getChaperonId());
            if (chaperon != null) {
                service.setName(chaperon.getName());
                service.setGender(chaperon.getGender());
                service.setPhone(chaperon.getPhone());
            }

            // 设置预约状态
            service.setIsBooked(serviceInfo.getIsBooked());

            return service;
        }).collect(Collectors.toList());

        // 查询总记录数
        long total = chaperonMapper.countServices();
        // 构建并返回PageResult对象
        return new PageInfo<>(total, servicesList);
    }

    /*
     *管理员下架陪诊服务
     */
    @Override
    public void deleteService(Integer id, String token) throws Exception {
        Claims claims = JwtUtils.parseToken(token);
        Integer identity = (Integer) claims.get("identity");
        if (identity != 3) {
            throw new Exception("需为管理员权限");
        }

        // 检查该陪诊服务是否存在
        if (chaperonMapper.selectServicesById(id) == null) {
            throw new Exception("该陪诊服务不存在");
        }
        chaperonMapper.deleteServiceById(id);
    }

    /*
     *获取陪诊列表,方便老人进行选择预约
     */
    @Override
    public PageInfo<Services> getServices(String service_date) {
        // 查询数据
        List<ServiceInfo> servicesInfoList = chaperonMapper.selectServicesListByDate(service_date);

        //转换为Services对象列表
        List<Services> servicesList = servicesInfoList.stream().map(serviceInfo -> {
            Services service = new Services();
            service.setId(serviceInfo.getId());
            service.setChaperonId(serviceInfo.getChaperonId());
            service.setDate(serviceInfo.getServiceDate());

            // 查询陪诊人员详细信息
            ChaperonInfo chaperon = chaperonMapper.selectChaperonById(serviceInfo.getChaperonId());
            if (chaperon != null) {
                service.setName(chaperon.getName());
                service.setGender(chaperon.getGender());
                service.setPhone(chaperon.getPhone());
            }

            // 直接使用数据库中的is_booked字段
            service.setIsBooked(serviceInfo.getIsBooked());

            return service;
        }).collect(Collectors.toList());
        long total = servicesList.size();
        // 构建并返回PageResult对象
        return new PageInfo<>(total, servicesList);
    }

    /*
     *预约陪诊服务
     */
    @Override
    public BookResponseDTO createNewServiceBook(BookInfo bookInfo, String token) throws Exception {
        Claims claims = JwtUtils.parseToken(token);
        Integer userId = (Integer) claims.get("id");
        
        // 通过服务ID直接查询服务信息
        ServiceInfo serviceInfo = chaperonMapper.selectServicesById(bookInfo.getId());
        if (serviceInfo == null) {
            throw new Exception("该陪诊服务不存在");
        }

        // 检查该服务是否已被预约
        if (serviceInfo.getIsBooked() != null && serviceInfo.getIsBooked()) {
            throw new Exception("该陪诊服务已被预约，请选择其他服务");
        }


        //  生成订单ID和预约时间（当前时间）
        Instant now = Instant.now();
        DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyyMMdd")
                .withZone(ZoneId.systemDefault());

        // 格式: BOOK + 年月日(8位) + 时间戳后4位 + 服务ID(补齐4位)，确保唯一性且包含服务ID
        String timestamp = String.valueOf(now.toEpochMilli());
        String timestampSuffix = timestamp.substring(timestamp.length() - 4);
        String orderId = "BOOK" + dateFormatter.format(now) + timestampSuffix + String.format("%04d", serviceInfo.getId());

        //  构建返回DTO
        BookResponseDTO responseDTO = new BookResponseDTO();
        responseDTO.setOrderId(orderId);
        responseDTO.setBookTime(Date.from(now)); // 转换为java.util.Date

        // 构建ServiceBookInfo
        ServiceBookInfo serviceBookInfo = new ServiceBookInfo();
        serviceBookInfo.setOrderId(orderId);
        serviceBookInfo.setBookTime(responseDTO.getBookTime());
        serviceBookInfo.setUserId(userId);
        serviceBookInfo.setChaperonId(serviceInfo.getChaperonId());
        serviceBookInfo.setDescriptionOfSymptoms(bookInfo.getDescriptionOfSymptoms());
        serviceBookInfo.setMedicalHistory(bookInfo.getMedicalHistory());
        serviceBookInfo.setAllergyHistory(bookInfo.getAllergyHistory());

        // 存入servicebook表
        chaperonMapper.insertServiceBook(serviceBookInfo);

        // 更新Services表中的is_booked字段为已预约
        chaperonMapper.updateServiceBookingStatus(serviceInfo.getChaperonId(), serviceInfo.getServiceDate(), true);

        return responseDTO;
    }

    /*
     *取消陪诊服务
     */
    @Override
    public void deleteServiceBook(String orderId) throws Exception {
        // 先获取完整的预约信息
        ServiceBookInfo serviceBookInfo = chaperonMapper.selectServiceBookInfoById(orderId);
        if (serviceBookInfo == null) {
            throw new Exception("该陪诊服务不存在");
        }
        
        log.info("取消预约，订单ID: {}", orderId);
        
        // 从订单号中提取服务ID（订单号格式：BOOK + 年月日(8位) + 时间戳后4位 + 服务ID(4位)）
        Integer serviceId = extractServiceIdFromOrderId(orderId);
        if (serviceId == null) {
            throw new Exception("订单号格式错误，无法提取服务ID");
        }
        
        // 删除预约记录
        chaperonMapper.deleteServiceBookById(orderId);
        
        // 直接通过服务ID查询服务记录并更新状态
        ServiceInfo serviceInfo = chaperonMapper.selectServicesById(serviceId);
        if (serviceInfo != null) {
            // 更新Services表的is_booked字段为false
            chaperonMapper.updateServiceBookingStatus(
                serviceInfo.getChaperonId(), 
                serviceInfo.getServiceDate(), 
                false
            );
        }
    }
    
    /**
     * 从订单号中提取服务ID
     * 订单号格式：BOOK + 年月日(8位) + 时间戳后4位 + 服务ID(4位)
     * 总长度：4 + 8 + 4 + 4 = 20位
     */
    private Integer extractServiceIdFromOrderId(String orderId) {
        try {
            if (orderId == null || orderId.length() != 20 || !orderId.startsWith("BOOK")) {
                return null;
            }
            // 提取最后4位作为服务ID
            String serviceIdStr = orderId.substring(16);
            return Integer.parseInt(serviceIdStr);
        } catch (NumberFormatException e) {
            log.error("从订单号提取服务ID失败: {}", orderId, e);
            return null;
        }
    }

    /*
     *用户获取陪诊列表
     */
    @Override
    public PageInfo<ServiceBookInfoDTO> getServiceBookList() {
        // 查询数据
        List<ServiceBookInfo> serviceBookInfoList = chaperonMapper.selectAllServiceBooks();

        // 转换为DTO对象列表
        List<ServiceBookInfoDTO> serviceBookInfoDTOList = serviceBookInfoList.stream().map(serviceBook -> {
            ServiceBookInfoDTO dto = new ServiceBookInfoDTO();
            dto.setOrderId(serviceBook.getOrderId());
            dto.setBookTime(serviceBook.getBookTime());
            dto.setChaperonId(serviceBook.getChaperonId());
            // 查询关联的陪诊人员信息
            ChaperonInfo chaperon = chaperonMapper.selectChaperonById(serviceBook.getChaperonId());
            if (chaperon != null) {
                dto.setName(chaperon.getName());
                dto.setGender(chaperon.getGender());
                dto.setPhone(chaperon.getPhone());
                dto.setIntroduction(chaperon.getIntroduction());
            }

            return dto;
        }).collect(Collectors.toList());

        // 查询总记录数
        long total = serviceBookInfoDTOList.size();
        // 构建并返回PageResult对象
        return new PageInfo<>(total, serviceBookInfoDTOList);
    }


}
